package com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.repository.impl;

import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.entity.KnowledgeManagement;
import com.css.fxfzxczh.modules.synthesizeInfoManage.knowledgeManagement.repository.KnowledgeManagementRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.matManage.entity.MatManage;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/01/11
 * @Description: 知识库管理
 */
@Repository
public class KnowledgeManagementRepositoryImpl implements KnowledgeManagementRepository {

    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private static final String TABLE_NAME = "xczh_knowledge_management"; // 表名
    private static final String TABLE_ID = "xkm_id"; // 表id字段名

    @Override
    public void save(KnowledgeManagement param) {
        String sql = "insert into " + TABLE_NAME +
                " (xkm_id,xsem_id,knowledge_code,knowledge_name," +
                "category,comment_info,attachment,attachment_name,file_type,company," +
                "del_flag,create_user,create_time)" +
                " values(:xkmId,:xsemId,:knowledgeCode,:knowledgeName," +
                ":category,:commentInfo,:attachment,:attachmentName,:fileType,:company," +
                ":delFlag,:createUser,:createTime)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(param);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void updateById(KnowledgeManagement param) {
        String sql = "update " + TABLE_NAME +
                " set knowledge_name = :knowledgeName,category = :category," +
                "comment_info = :commentInfo,file_type=:fileType,";
        if (!PlatformObjectUtils.isEmpty(param.getAttachment())) {
            sql = sql + " attachment=:attachment,";
        }
        if ("1".equals(param.getXkmId())) {
            sql = sql + " xsem_id=:xsemId,";
        }
        sql = sql + "update_user=:updateUser,update_time=:updateTime where del_flag = '0' and " + TABLE_ID + " = '"+param.getXkmId()+"'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(param);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void deleteById(String id) {
        String sql = "update " + TABLE_NAME + " set del_flag = ?  where " + TABLE_ID + " = ?";
        jdbcTemplate.update(sql, YNEnum.Y.toString(),id);
    }

    @Override
    public Map<String, Object> getPage(KnowledgeManagement queParams, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from " + TABLE_NAME);
        StringBuilder whereSql = new StringBuilder(" where del_flag = '0'");
        StringBuilder orderSql = new StringBuilder(" order by create_time desc");
        int firstIndex = (curPage - 1) * pageSize;
        int lastIndex = pageSize;
        StringBuilder limitSql = new StringBuilder(" limit " + lastIndex + " offset " + firstIndex);
        //知识库类型
        if (!PlatformObjectUtils.isEmpty(queParams.getCategory())) {
            whereSql.append(" and category = '" + queParams.getCategory() + "'");
//            if (queParams.getCategory().equals("2")){
//                whereSql.append(" and xsem_id = '" + queParams.getXsemId() + "'");
//            }
//            if (queParams.getCategory().equals("1")){
//                whereSql.append(" and xsem_id = '1'");
//            }
        }
        if(!PlatformObjectUtils.isEmpty(queParams.getXsemId())){
            whereSql.append(" and xsem_id = '" + queParams.getXsemId() + "'");
        }
        //知识库名称
        if (!PlatformObjectUtils.isEmpty(queParams.getKnowledgeName())) {
            whereSql.append(" and knowledge_name like '%" + queParams.getKnowledgeName() + "%'");
        }

        sql.append(whereSql).append(orderSql);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(KnowledgeManagement.class)).size();
        List<KnowledgeManagement> list = jdbcTemplate.query(sql.append(limitSql).toString(), new BeanPropertyRowMapper<>(KnowledgeManagement.class));
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    @Override
    public void updateFile(KnowledgeManagement param) {
        String sql = "update " + TABLE_NAME +
                " set attachment=:attachment,attachment_name = :attachmentName ,file_type=:fileType," +
                "update_user=:updateUser,update_time=:updateTime where " + TABLE_ID + " = '" + param.getXkmId() + "'";
        SqlParameterSource source = new BeanPropertySqlParameterSource(param);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public String getCode(String xsemId) {
        String sql = "select knowledge_code from " + TABLE_NAME + " where ";
        if (!PlatformObjectUtils.isEmpty(xsemId)) {
            sql = sql + " xsem_id = '" + xsemId + "' and ";
        }
        sql = sql + "del_flag ='0' order by create_time desc limit 1";
        try {
            return jdbcTemplate.queryForObject(sql, String.class);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    @Override
    public void batchSave(List<KnowledgeManagement> list) {
        SqlParameterSource[] beanSources = SqlParameterSourceUtils.createBatch(list.toArray());
        String sql = "INSERT INTO "+TABLE_NAME+" (xkm_id,xsem_id,knowledge_code,knowledge_name,category,comment_info,del_flag,create_user,create_time)" +
                "values (:xkmId,:xsemId,:knowledgeCode,:knowledgeName,:category,:commentInfo,:delFlag,:createUser,:createTime)";
        namedParameterJdbcTemplate.batchUpdate(sql, beanSources);
    }

    @Override
    public List<KnowledgeManagement> queryByParam(KnowledgeManagement queParams) {
        StringBuilder sql = new StringBuilder("select * from " + TABLE_NAME);
        StringBuilder whereSql = new StringBuilder(" where del_flag = '0'");
        StringBuilder orderSql = new StringBuilder(" order by create_time desc");
        //知识库类型
        if (!PlatformObjectUtils.isEmpty(queParams.getCategory())) {
            whereSql.append(" and category = '" + queParams.getCategory() + "'");
            if (queParams.getCategory().equals("信息库")){
                whereSql.append(" and xsem_id = '" + queParams.getXsemId() + "'");
            }
            if (queParams.getCategory().equals("基础知识库")){
                whereSql.append(" and xsem_id = '1'");
            }
        }else {
            //如果不传类型则两个一起查
            whereSql.append(" and xsem_id in( '" + queParams.getXsemId() + "','1')");
        }
        //知识库名称
        if (!PlatformObjectUtils.isEmpty(queParams.getKnowledgeName())) {
            whereSql.append(" and knowledge_name like '%" + queParams.getKnowledgeName() + "%'");
        }
        sql.append(whereSql).append(orderSql);
        return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(KnowledgeManagement.class));
    }

    @Override
    public KnowledgeManagement findById(String param) {
        String sql = "select * from " + TABLE_NAME + " where " + TABLE_ID + " = '" + param + "'";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(KnowledgeManagement.class));
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    @Override
    public void updateXsemId(String xsemId, String convertedXsemId) {
        String sql = "update "+TABLE_NAME+" set xsem_id = '"+xsemId+"'  where xsem_id = '"+convertedXsemId+"'";
        jdbcTemplate.update(sql);
    }

    @Override
    public String getXsemCode(String xsemId) {
        String sql = "select event_code from  xczh_seismic_event_management where  xsem_id = '" + xsemId + "' ";
        try {
            return jdbcTemplate.queryForObject(sql, String.class);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    @Override
    public String getMaxNum(String str) {
        String sql="select max(knowledge_code) from xczh_knowledge_management where del_flag = '0' and knowledge_code like '%"+str+"%'";
        String maxNum=jdbcTemplate.queryForObject(sql,String.class);
        return maxNum;
    }
}
